package com.gulimall.order.config;

import com.gulimall.order.domain.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DelayQueueConfig {
    /**
     * 容器中的Binding,Queue,Exchange都会自动创建（前提是rabbitmq中没有）
     * @return
     */

    //String name, boolean durable, boolean exclusive, boolean autoDelete, @Nullable Map<String, Object> arguments
    @Bean
    public Queue orderDelayQueue(){
        //延迟队列相关数据
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","order-event-exchange");
        arguments.put("x-dead-letter-routing-key","order.release.order");
        arguments.put("x-message-ttl",60000);
        return new Queue("order.delay.queue",true,false,false,arguments);
    }
    //order.release.order.queue
    @Bean
    public Queue orderReleaseOrderQueue(){
        return new Queue("order.release.order.queue",true,false,false);
    }
    //String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
    @Bean
    public Exchange orderEventExchange(){
        return new TopicExchange("order-event-exchange",true,false);
    }

    //@Nullable String destination, DestinationType destinationType, String exchange,
    // @Nullable String routingKey, @Nullable Map<String, Object> arguments
    @Bean
    public Binding bindingOrderDelayQueue(){
        return new Binding(
                "order.delay.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.create.order",
                null
        );
    }

    @Bean
    public Binding bindingOrderReleaseOrderQueue(){
        return new Binding(
                "order.release.order.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.release.order",
                null
        );
    }

    /**
     * 监听队列order.release.order.queue消息
     * deliveryTag：消息的唯一标识（在当前信道内递增）。
     * multiple：是否批量确认。
     */
    @RabbitListener(queues = "order.release.order.queue")
    public void listener(Order order, Message message, Channel channel) throws IOException {
        System.out.println("收到过期的订单信息，准备关闭订单：" + order.getOrderSn());
        //消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
